from datetime import timedelta

from flask import request, session
from flask_restful import Resource

from database import Database


# Mock user database
class booksReturn(Resource):
    def post(self):
        db = Database()
        user_id = session.get('username')
        if user_id is None:
            return {'message': 'You are not logged in!'}, 401
        else:
            data = request.get_json()
            status = 'in process'

            bookId = data.get('bookId')
            print(bookId)

            quantity = len(bookId)

            class1 = 'Return'
            orderId = db.execute_query("SELECT * FROM orderids ")

            orderId1 = str(orderId[0])
            if orderId1 is not None:
                db.execute_query(
                    "INSERT INTO `order` (orderId, userId, status,quantity,class) VALUES (%s,  %s, %s, %s,%s)",
                    (orderId1, user_id, status, quantity, class1))
                db.execute_query("UPDATE orderids SET OrderID = OrderID + 1")
                order = db.execute_query("SELECT * FROM `order` WHERE orderId = %s", (orderId1,))

                dateCreated = order[2]
                new_date = dateCreated + timedelta(days=14)
                print(new_date)
                for bookId_value in bookId.values():
                    db.execute_query(
                        "INSERT INTO `linebook` (orderId, userId, status, bookId, libraryAddress, borrowedTill) VALUES (%s, %s, %s, %s, %s, %s)",
                        (orderId1, user_id, 'borrowed', bookId_value, None, new_date))

                print(orderId1)
                order = db.execute_query("SELECT * FROM `order` WHERE orderId = %s", (orderId1,))
                if order:
                    order = {
                        "orderId": order[0],
                        "userId": order[1],
                        "date": order[2].strftime("%Y-%m-%d %H:%M:%S"),
                        "status": order[3],
                        "quantity": order[4],
                        "class": order[5]
                    }
                    return {"order": order}, 200
                else:
                    return {'message': 'Order not found'}, 404
            else:
                return {"message": "insert a order fail"}, 409  # Changed return status to 409 Conflict
